/*******************************************************************************
 * Copyright 2018 The MIT Internet Trust Consortium
 *
 * Portions copyright 2011-2013 The MITRE Corporation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *******************************************************************************/
package org.mitre.openid.connect.repository.impl;

import static org.apache.http.util.TextUtils.isBlank;
import static org.mitre.util.jpa.JpaUtil.getSingleResult;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;

import org.mitre.openid.connect.dto.OrgDto;
import org.mitre.openid.connect.dto.UserDto;
import org.mitre.openid.connect.model.DefaultUserInfo;
import org.mitre.openid.connect.model.UserInfo;
import org.mitre.openid.connect.repository.UserInfoRepository;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * JPA UserInfo repository implementation
 *
 * @author Michael Joseph Walsh
 *
 */
@Repository("jpaUserInfoRepository")
public class JpaUserInfoRepository implements UserInfoRepository {

	@PersistenceContext(unitName="ssoPersistenceUnit")  //defaultPersistenceUnit
	private EntityManager manager;

	/**
	 * Get a single UserInfo object by its username
	 */
	@Override
	public UserInfo getByUsername(String username) {
		TypedQuery<DefaultUserInfo> query = manager.createNamedQuery(DefaultUserInfo.QUERY_BY_USERNAME, DefaultUserInfo.class);
		query.setParameter(DefaultUserInfo.PARAM_USERNAME, username);

		return getSingleResult(query.getResultList());

	}

	/**
	 * 获取用户的组织和
	 */
	public ArrayList<HashMap<String, String>> getOrgByUserCode(String userCode) {

		String jpql = "select d.id,OrgCode,OrgName,OrgIdPath from jobusers a inner join orgjobs b on a.OrgJobId=b.id "+
			"inner join orgs d on b.OrgId=d.id inner join dataversion c on a.VersionNo= c.VersionNo and b.VersionNo=c.VersionNo and d.VersionNo=c.VersionNo "+
			" where UserId = ? "+
		    "union "+
		    "select a.id,a.OrgCode,a.OrgName,a.OrgIdPath from orgs a join orgusers b on a.id=b.OrgId "+
		    "join users c on b.UserId=c.Id "+
		    "join dataversion d on a.VersionNo=d.VersionNo "+
		    "where c.Id=?";
		Query query = manager.createNativeQuery(jpql).setParameter(1, userCode).setParameter(2,userCode);

		ArrayList<HashMap<String, String>> datas = new ArrayList<HashMap<String, String>>();
		List<Object[]> orgs = query.getResultList();
		System.out.println("length:" + orgs.size());

		OrgDto orgDto = new OrgDto();

		for(Object[] dto:orgs) {

			//orgDto.setId(dto[0]+",");
			//orgDto.setOrgCode(dto[1]+",");
			//orgDto.setOrgName(dto[2]+",");
			//orgDto.setOrgIdPath(dto[3]+",");

			HashMap<String, String> map = new HashMap<String, String>();
			map.put("Id",dto[0]+"");
			map.put("OrgCode",dto[1]+"");
			map.put("OrgName",dto[2]+"");
			map.put("OrgIdPath",dto[3]+"");
			datas.add(map);
		}

	    //	if(orgDto.getId() != null) {
	    //		orgDto.setId(orgDto.getId().substring(0, orgDto.getId().length() - 1));
	    //	}
        //
	    //	if(orgDto.getOrgCode() != null) {
	    //		orgDto.setOrgCode(orgDto.getOrgCode().substring(0, orgDto.getOrgCode().length() - 1));
	    //	}
        //
	    //	if(orgDto.getOrgName() != null) {
	    //		orgDto.setOrgName(orgDto.getOrgName().substring(0, orgDto.getOrgName().length() - 1));
	    //	}
        //
	    //	if(orgDto.getOrgIdPath() != null) {
	    //		orgDto.setOrgIdPath(orgDto.getOrgIdPath().substring(0, orgDto.getOrgIdPath().length() - 1));
	    //	}


		return datas;

	}
	public List getRoleByUserCode(String clientId, String userCode){

		String jpql = "select r.RoleName from apps a join roles r on a.Id=r.AppId and a.ValidStatus=1 and r.ValidStatus=1 " +
			"join roleusers ru on r.Id=ru.RoleId and ru.ValidStatus=1 " +
			"join users u on u.UserCode=ru.UserId and u.AccountIsDisabled=0 " +
			"join dataversion d on d.VersionNo=u.VersionNo " +
			"WHERE a.AppCode=? and u.UserCode=?";

		Query query = manager.createNativeQuery(jpql).setParameter(1, clientId).setParameter(2,userCode);

		//String jpql = "select RoleName from  roles";
//
		//Query query = manager.createNativeQuery(jpql);
		List list =query.getResultList();
		return  list;
	}


	/**
	 *根据钉钉ID获取用户信息
	 * @param dingUserId
	 * @return
	 */
	public UserDto getUserByDingId(String dingUserId){
		UserDto udto=new UserDto();
		String sql="select Id,UserCode,UserName from v_users where DingUserId= ?";
		Query query = manager.createNativeQuery(sql).setParameter(1, dingUserId);
		List<Object[]> users = query.getResultList();

		if(users.size()==0){
			return null;
		}else {
			for (Object[] dto : users) {
				udto.setId(dto[0] == null ? "" : dto[0].toString());
				udto.setUserCode(dto[1] == null ? "" : dto[0].toString());
				udto.setUserName(dto[2] == null ? "" : dto[0].toString());
			}
		}
		return udto;
	}




	/**
	 * Get a single UserInfo object by its email address
	 */
	@Override
	public UserInfo getByEmailAddress(String email) {
		TypedQuery<DefaultUserInfo> query = manager.createNamedQuery(DefaultUserInfo.QUERY_BY_EMAIL, DefaultUserInfo.class);
		query.setParameter(DefaultUserInfo.PARAM_EMAIL, email);

		return getSingleResult(query.getResultList());
	}

}
